<template>
  <div>
    <div class="top">
      <div class="search">
        <el-form :model="searchParams" label-width="150px" inline>
          <el-form-item :label="t('userName')">
            <el-input v-model="searchParams.user_name" :placeholder="t('pleaseInput')"></el-input>
          </el-form-item>
          <el-form-item :label="t('userId')">
            <el-input v-model="searchParams.user_id" :placeholder="t('pleaseInput')"></el-input>
          </el-form-item>
          <el-form-item :label="t('orderNo')">
            <el-input v-model="searchParams.order_no" :placeholder="t('pleaseInput')"></el-input>
          </el-form-item>
          <el-form-item :label="t('orderId')">
            <el-input v-model="searchParams.order_id" :placeholder="t('pleaseInput')"></el-input>
          </el-form-item>
          <el-form-item :label="t('orderStatus')">
            <el-select clearable v-model="searchParams.order_status" style="width: 180px"
                       :placeholder="t('pleaseSelect')">
              <el-option
                v-for="option in orderStatusOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="t('repayConfigId')">
            <el-input v-model="searchParams.pay_config_id" :placeholder="t('pleaseSelect')"></el-input>
          </el-form-item>
          <el-form-item :label="t('startCreateTime')">
            <el-date-picker
              v-model="searchParams.start_create_time"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :placeholder="t('pleaseSelect')"
            />
          </el-form-item>
          <el-form-item :label="t('endCreateTime')">
            <el-date-picker
              v-model="searchParams.end_create_time"
              type="datetime"
              :placeholder="t('pleaseSelect')"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
          <el-form-item :label="t('startUpdateTime')">
            <el-date-picker
              v-model="searchParams.start_update_time"
              type="datetime"
              :placeholder="t('pleaseSelect')"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item :label="t('endUpdateTime')">
            <el-date-picker
              v-model="searchParams.end_update_time"
              type="datetime"
              :placeholder="t('pleaseSelect')"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">{{ t('query') }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-table class="table_content" :data="state.orderList" :border="true" v-loading="loading">
      <el-table-column prop="product_id" :label="t('productId')" width="60"></el-table-column>
      <el-table-column prop="id" :label="t('orderId')" width="60"></el-table-column>
      <el-table-column prop="order_no" :label="t('orderNo')"></el-table-column>
      <el-table-column prop="user_id" :label="t('userId')" width="60"></el-table-column>
      <el-table-column prop="order_status" :label="t('orderStatus')">
        <template v-slot="{ row }">
          <el-tag>{{ orderStatusDescriptions[row.order_status] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="num_loan" :label="t('loanNum')" width="60"></el-table-column>
      <el-table-column prop="application_amount" :label="t('loanAmount')">
        <template v-slot="{ row }">
          Rp {{ row.application_amount }}
        </template>
      </el-table-column>
      <el-table-column :label="t('loanPeriod')" width="60">
        <template v-slot="{ row }">
          {{ row.application_term }}{{ row.term_unit === 1 ? t('day') : t('month') }}
        </template>
      </el-table-column>
      <el-table-column :label="t('isOverdue')" width="60">
        <template v-slot="{row}">
          <el-tag type="danger" v-if="row.has_overdue === 1">{{ t('yes') }}</el-tag>
          <el-tag type="success" v-else>{{ t('no') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="pay_config_id" :label="t('repayConfigId')" width="68"></el-table-column>
      <el-table-column prop="idcard" :label="t('idCard')" width="120" />
      <el-table-column
        prop="confirm_time"
        :label="t('approveSuccessTime')"
      />
      <el-table-column
        prop="loan_time"
        :label="t('loanSuccessTime')"
      />
      <el-table-column
        prop="payoff_time"
        :label="t('payoffTime')"
      />
      <el-table-column
        prop="create_time"
        :label="t('createTime')"
      />
      <el-table-column
        prop="update_time"
        :label="t('updateTime')"
      />
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="state.total"
    >
    </el-pagination>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, toRefs, onMounted, watch } from 'vue'
import {
  ElTable,
  ElTableColumn,
  ElPagination,
  ElTag,
  ElButton, ElMessage
} from 'element-plus'
import { useRouter } from 'vue-router'
import { getOrderList } from '@/api/order'
import { storeToRefs } from 'pinia'
import useRepaySchemeStore from '@/stores/repaySchemeStore'
import { OrderStatus, orderStatusDescriptions } from '@/utils/orderStatus'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()
const router = useRouter()
let loading = ref(false)

onMounted(() => {
  // repaySchemeStore.getProductList()
  loadData()
})

// 计算属性，用于转换枚举值为下拉菜单的选项
const orderStatusOptions = computed(() => {
  return Object.entries(orderStatusDescriptions).map(([value, label]) => ({
    value: parseInt(value), // 将枚举的字符串值转换为数字
    label
  }))
})

// 查询参数的响应式数据
const searchParams = ref({
  product_id: '',
  user_name: '',
  user_id: '',
  order_no: '',
  order_id: '',
  order_status: '',
  start_create_time: '',
  end_create_time: '',
  start_update_time: '',
  end_update_time: '',
  pay_config_id: ''
})

const handleSearch = () => {
  // 校验开始更新时间不能小于结束更新时间
  if (searchParams.value.start_update_time && searchParams.value.end_update_time) {
    if (searchParams.value.start_update_time > searchParams.value.end_update_time) {
      ElMessage.error(t('endUpdateTimeMustLaterThanStartUpdateTime'))
      return
    }
  }
  // 开始创建时间不能小于结束创建时间
  if (searchParams.value.start_create_time && searchParams.value.end_create_time) {
    if (searchParams.value.start_create_time > searchParams.value.end_create_time) {
      ElMessage.error(t('endCreateTimeMustLaterThanStartCreateTime'))
      return
    }
  }
  console.log('searchParams:', searchParams.value)
  loadData()
}

function loadData() {
  loading.value = true
  const filteredParams = filterEmptyParams(searchParams.value)
  console.log('filteredParams:', filteredParams)
  filteredParams['page_no'] = currentPage.value
  filteredParams['page_size'] = pageSize.value
  getOrderList(filteredParams)
    .then((res) => {
      state.value.orderList = res.order_list
      state.value.total = res.total
    })
    .catch((err) => {
      console.log('err:', err)
    }).finally(() => {
    loading.value = false
  })
}

function filterEmptyParams(params) {
  return Object.entries(params).reduce((acc, [key, value]) => {
    if (value != undefined && value != '') {
      acc[key] = value
    }
    return acc
  }, {})
}


const state = ref({
  orderList: [],
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const handleSizeChange = (newSize: any) => {
  state.value.pageSize = newSize
}

const handleCurrentChange = (newPage: any) => {
  state.value.currentPage = newPage
  console.log('newPage:', newPage)
  loadData()
}

// 导出响应式状态的引用
const { currentPage, pageSize } = toRefs(state.value)
</script>

<style scoped lang="scss">
.top {
  width: 98%;
  margin-top: 28px;
  margin-bottom: 10px;

  .add {
    float: right;
  }

  .status {
    width: 180px;
  }
}

.table_content {
  width: 98%;
  margin-top: 20px;
}
</style>
